<template>
  <view class="chatLayout">
    <!-- scroll-with-animation 在设置滚动条位置时使用动画过渡 -->
    <!-- scroll-top   设置竖向滚动条位置 -->

    <scroll-view :style="{height: `${windowHeight-inputHeight}rpx`}" id="scrollview" scroll-y="true"
                 class="scroll-view" :scroll-top="scrollTop" :scroll-with-animation="true">
      <!-- 聊天主体 -->
      <view id="msglistview" class="chat-body">
        <!-- 聊天记录 -->
        <view v-for="(item,index) in msgList" :key="index">
          <!-- 自己发的消息 -->
          <view class="item self" v-if="item.userContent != ''">
            <!-- 文字内容 -->
            <view class="content right">
              {{item.userContent}}
            </view>
            <!-- 头像 -->
            <image  :src="fromuser.avatar"
                    mode="mode" class="avatar"></image>
<!--            <text class="username">{{fromuser.name}}</text>-->
          </view>

          <!-- 好友发来的消息的消息 -->
          <view class="item touser" v-if="item.botContent != '' ">
            <text class="username">{{touser.name}}</text>
            <image :src="touser.avatar"
                   mode="mode" class="avatar"></image>
            <view class="content left" v-if="item.isLoading">
              <view class="inital">
                <view class="loading-spinner"></view>
                <view class="ponder">正在思考...</view>
              </view>
            </view>
            <view class="content left" v-else>
              <text> {{item.botContent.replace(/\\n/g,'\n')}}</text>
            </view>
          </view>
        </view>

      </view>
    </scroll-view>
    <!-- 底部消息发送栏 -->
    <!-- 用来占位，防止聊天消息被发送框遮挡 -->
    <view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
      <view class="send-msg" :style="{bottom:`${keyboardHeight}rpx`}">
        <view class="uni-textarea">
          <!-- maxlength 	最大输入长度，设置为 -1 的时候不限制最大长度 -->
          <!-- show-confirm-bar  -->
          <!-- adjust-position 键盘弹起时，是否自动上推页面 -->
          <!-- @linechange 输入框行数变化时调用， -->
          <!-- show-confirm-bar  是否显示键盘上方带有”完成“按钮那一栏 -->
          <!-- auto-height 是否自动增高 -->
          <textarea v-model="chatMsg" maxlength="300" confirm-type="send" @confirm="handleSend"
                    :show-confirm-bar="false" :adjust-position="false" @linechange="sendHeight" @focus="focus"
                    @blur="blur" auto-height></textarea>
        </view>
        <button class="send-btn" @click="handleSend">发送</button>
      </view>
    </view>
  </view>
</template>
<script setup>
import { messageHistory ,connectChatWebSocket} from '@/apis/chatAPI';
import {ref, computed, onMounted, getCurrentInstance,onUnmounted} from 'vue';
import { onLoad } from '@dcloudio/uni-app'
const chatMsg = ref('')
const scrollTop = ref(0);
const bottomHeight = ref(0);
const keyboardHeight = ref(0);
const msgList = ref([])
// 1. 声明 socket 变量（使用 ref 响应式变量）
const socket = ref(null); // 关键：定义 socket 变量
// 单位转换
const rpxTopx = (px) => {
  const deviceWidth = uni.getSystemInfoSync().windowWidth;
  const rpx = (750 / deviceWidth) * Number(px);
  return Math.floor(rpx);
};
const windowHeight = computed(() => {
  return rpxTopx(uni.getSystemInfoSync().windowHeight)
});
const inputHeight = computed(() => {
  return bottomHeight.value + keyboardHeight.value;
});
const currentUser = {
  id: '',
  name: '',
  avatar: ''
};
onMounted(() => {
  scrollToBottom();
  // 监听键盘高度变化
  uni.onKeyboardHeightChange((res) => {
    //为了不让键盘和聊天输入框之间距离差太大
    keyboardHeight.value = rpxTopx(res.height - 30)
    if (keyboardHeight.value < 0) keyboardHeight.value = 0;
  })
})
const focus = () => {
  scrollToBottom();
};
const touser = ref({
  name: '',
  avatar: '',
  userId: ''
});
const userInfo = uni.getStorageSync('userInfo');
const fromuser = ref({
  name: userInfo.username,
  // name: userInfo.nickname,

  avatar: userInfo.avatar,
  userId: userInfo.userId
});

const blur = () => {
  scrollToBottom();
};
const instance = getCurrentInstance();
const sendHeight = () => {
  setTimeout(() => {
    const query = uni.createSelectorQuery().in(instance.proxy);
    query.select('.send-msg').boundingClientRect();
    query.exec((res) => {
      bottomHeight.value = rpxTopx(res[0].height);
    });
  }, 10)


};
onLoad((query) => {
  // 将URL参数赋值给响应式对象
  touser.value = {
    name: query.name || '', // 提供默认值
    avatar: query.avatar || '',
    userId: query.userId || ''
  };
  const userInfo = uni.getStorageSync('userInfo');
  currentUser.value = {
    id: userInfo.userId,
    name: userInfo.username,
    // name: userInfo.nickname,
    avatar: userInfo.avatar
  };
  console.log('1:',touser.value.userId,'2:',currentUser.value.id)

  socket.value = connectChatWebSocket(touser.value.userId,currentUser.value.id)
  console.log('聊天websocket连接成功')

  // 建立WebSocket连接
  // socket.value = uni.connectSocket({
  //   url: `ws://localhost:10000/ws/chat/${touser.value.userId}/${currentUser.value.id}`,
  // });

  // 监听错误
  uni.onSocketError((err) => {
    console.error('聊天连接错误：', err); // 关键：打印错误详情
  });

  // 监听消息
  uni.onSocketMessage(res => {
    console.log('接收到的消息：555', res.data);
    const msg = JSON.parse(res.data);

    if (msg.type === 'MESSAGE') {
      // 关键：只添加对方发送的消息（排除自己发送的消息）
      // 假设后端返回的消息中，有 senderId 字段标识发送者
      if (msg.senderId !== currentUser.value.id) {
        msgList.value.push({
          botContent: msg.content,  // 对方消息显示在左侧
          userContent: "",           // 自己消息为空
          isLoading: false
        });

        scrollToBottom(); // 收到消息后滚动到底部
      }
    }
  });

  // 加载历史消息
  loadHistory();

  // 打印验证
  console.log('接收的用户信息:', touser.value.name)
});
// 加载历史消息
const loadHistory=()=>{
  console.log("userId1",currentUser.value.id)
  console.log("userId",touser.value.userId)
  messageHistory(currentUser.value.id, touser.value.userId, 0, 20)
      .then(res => {
        console.log("查詢的聊天歷史",res)
        res.data.forEach(msg => {
          // 都转为字符串后对比
          const senderIdStr = String(msg.senderId);
          const currentIdStr = String(currentUser.value.id);
          msgList.value.unshift({
            userContent: senderIdStr === currentIdStr ? msg.content : "",
            botContent: senderIdStr !== currentIdStr ? msg.content : ""
          });
        });
        scrollToBottom();
      })
      .catch(err => {
        console.error('加载历史消息失败：', err);
      })
};

const scrollToBottom = () => {
  // nextTick(() => {
  setTimeout(() => {
    const query = uni.createSelectorQuery().in(instance.proxy);
    query.select('#scrollview').boundingClientRect();
    query.select('#msglistview').boundingClientRect();
    query.exec((res) => {
      if (res[1].height > res[0].height) {
        scrollTop.value = rpxTopx(res[1].height - res[0].height)
      }
    })
  }, 15)

};
// 发送消息
// 修改后的handleSend函数
const handleSend = () => {
  chatMsg.value = chatMsg.value || ''; // 防止 undefined
  const content = chatMsg.value.trim();
  if (!content) return;

  const tempId = Date.now(); // 生成临时ID用于追踪消息
  const tempMsg = {
    id: tempId, // 添加唯一标识
    userContent: content,
    botContent: "",
    isSending: true // 添加发送状态标记
  };

  // 临时添加到消息列表（显示发送中状态）
  msgList.value.push(tempMsg);
  chatMsg.value = '';
  scrollToBottom();

  const msg = {
    toUserId: touser.value.userId,
    content: content
  };

  // 通过WebSocket发送
  uni.sendSocketMessage({
    data: JSON.stringify(msg),
    success: () => {
      // 发送成功：更新消息状态
      const index = msgList.value.findIndex(m => m.id === tempId);
      if (index !== -1) {
        msgList.value[index].isSending = false;
      }
    },
    fail: (err) => {
      console.error('消息发送失败', err);
      // 发送失败：移除临时消息
      const index = msgList.value.findIndex(m => m.id === tempId);
      if (index !== -1) {
        msgList.value.splice(index, 1);
      }
      uni.showToast({
        title: '消息发送失败',
        icon: 'none'
      });
    }
  });
};

onUnmounted(() => {
  if (socket.value) {
    uni.closeSocket(); // 关闭连接
    console.log('聊天连接关闭')
  }
  // 离开聊天页面时刷新消息列表
  const pages = getCurrentPages();
  const prevPage = pages[pages.length - 2]; // 获取上一个页面实例
  if (prevPage && prevPage.$vm.fetchMessages) {
    prevPage.$vm.fetchMessages();
  }
});

</script>
<style lang="scss" scoped>
$chatContentbgc: #C2DCFF;
$sendBtnbgc: #4F7DF5;

view,
button,
text,
input,
textarea {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.chatLayout {
  .scroll-view {
    background-color: #F6F6F6;
    // background-color: pink;

    ::-webkit-scrollbar {
      display: none;
      width: 0 !important;
      height: 0 !important;
      -webkit-appearance: none;
      background: transparent;
      color: transparent;
    }

    .chat-body {
      // background-color: yellow;
      display: flex;
      flex-direction: column;
      padding-top: 23rpx;

      .self {
        justify-content: flex-end;
      }

      .item {
        display: flex;
        padding: 23rpx 30rpx;
        // background-color: skyblue;
        // background-color: lightpink;

        .content {
          position: relative;
          background-color: palevioletred;
          max-width: 486rpx;
          border-radius: 8rpx;
          // ：允许在单词内部断行，防止溢出。
          word-wrap: break-word;
          padding: 24rpx 24rpx;
          margin: 0 24rpx;
          border-radius: 5rpx;
          font-size: 32rpx;
          color: #333;
          line-height: 42rpx;

        }

        .right {
          background-color: $chatContentbgc;
          // background-color: lavenderblush;
        }

        .left {
          background-color: #FFFFFF;

          // background-color: lemonchiffon;
          .inital {
            display: flex;
            align-items: center;

            .loading-spinner {
              width: 30rpx;
              height: 30rpx;
              border: 3px solid #f3f3f3;
              border-top: 3px solid #3498db;
              border-radius: 50%;
              animation: spin 1s linear infinite;
              margin-right: 10rpx;

              @keyframes spin {
                0% {
                  transform: rotate(0deg);
                }

                100% {
                  transform: rotate(360deg);
                }
              }
            }
          }
        }

        // 聊天消息的三角形
        .right::after {
          position: absolute;
          display: inline-block;
          content: '';
          width: 0;
          height: 0;
          left: 100%;
          top: 10px;
          border: 12rpx solid transparent;
          border-left: 12rpx solid $chatContentbgc;

        }

        .left::after {
          position: absolute;
          display: inline-block;
          content: '';
          width: 0;
          height: 0;
          top: 10px;
          right: 100%;
          border: 12rpx solid transparent;
          border-right: 12rpx solid #FFFFFF;

        }

        .avatar {
          display: flex;
          justify-content: center;
          width: 78rpx;
          height: 78rpx;
          border-radius: 50rpx;
          overflow: hidden;

          image {
            align-self: center;
          }

        }
      }
    }

  }

  // 底部聊天发送栏
  .chat-bottom {
    // background-color: skyblue;
    padding-bottom: env(safe-area-inset-bottom);
    width: 100%;
    height: 100rpx;
    background: #F4F5F7;
    transition: all 0.1s ease;

    .send-msg {
      // background-color: pink;
      display: flex;
      align-items: flex-end;
      padding: 16rpx 30rpx;
      width: 100%;
      min-height: 177rpx;
      position: fixed;
      bottom: 0;
      background: #fff;
      // background: palegoldenrod;
      transition: all 0.1s ease;
    }

    .uni-textarea {
      // background-color: skyblue;
      padding-bottom: 70rpx;

      textarea {
        width: 537rpx;
        min-height: 75rpx;
        background: #f1f1f1;
        // background-color: steelblue;
        border-radius: 40rpx;
        font-size: 32rpx;
        font-family: PingFang SC;
        color: #333;
        line-height: 75rpx;
        padding: 5rpx 8rpx;
        text-indent: 30rpx;
      }
    }

    .send-btn {
      // background-color: pink;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 76rpx;
      margin-left: 25rpx;
      width: 120rpx;
      height: 75rpx;
      background: #ed5a65;
      border-radius: 50rpx;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #FFFFFF;
      line-height: 28rpx;

    }
  }

}
</style>